package io.zhengsh.thread;

import io.zhengsh.util.HttpHeaderUtil;
import io.zhengsh.util.RandomUtil;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class WorkThread implements Runnable {

    private static AtomicInteger count = new AtomicInteger(0);


    private final List<String> pages = new ArrayList<>();


    public WorkThread(Map<String, List<String>> map) {
        map.forEach((k, li) -> pages.addAll(li));
    }

    @Override
    public void run() {
        int len = RandomUtil.randomNum(2000);
        len = Math.max(len, 1000);
        System.out.println(String.format("request: client %s start , max count: %d", Thread.currentThread().getName(), len));
        for (int i = 0; i < len; i++) {
            String now = String.valueOf(System.currentTimeMillis());
            String url = pages.get(RandomUtil.randomNum(pages.size() - 1));
            try {
                Connection connect = Jsoup.connect(url);
                //登录请求 Connection.Response loginResponse =

                connect.method(Connection.Method.GET)
                        .header(HttpHeaderUtil.USER_AGENT, HttpHeaderUtil.getUserAgent())
                        .headers(HttpHeaderUtil.createHttpHeaders())
                        .execute();
                //System.out.println(connect.get());
                int i1 = count.addAndGet(1);
                System.out.println(String.format("request: now: %s client %s  count: %d page url: %s success", now, Thread.currentThread().getName(), i1, url));
                RandomUtil.randomSleepByWorkDate();
            } catch (Throwable t) {
                System.err.println(String.format("request: client %s  page url: %s error", Thread.currentThread().getName(), url));
                t.printStackTrace();
            }
        }
    }


}
